<template>
  <div class="health-report-container">
    <div class="app-container">
      <!-- 头部区域 -->
      <div class="report-header">
        <div>
          <h1 class="report-title">健康报告</h1>
          <p class="report-subtitle">全面了解您的健康状况</p>
        </div>

        <div class="header-controls">
          <!-- 时间范围选择器 -->
          <div class="time-selector">
            <el-button
              v-for="tab in tabs"
              :key="tab.key"
              :type="activeTab === tab.key ? 'primary' : 'default'"
              @click="switchTab(tab.key)"
              plain
            >
              <i :class="tab.iconClass"></i>
              {{ tab.label }}
            </el-button>
          </div>

          <!-- 历史报告选择区域 -->
          <div class="history-selector">
            <el-date-picker
              ref="historyDatePicker"
              v-model="selectedHistoryDate"
              :key="activeTab"
              :type="activeTab === 'daily' ? 'date' : activeTab === 'weekly' ? 'week' : 'month'"
              :format="activeTab === 'daily' ? 'yyyy-MM-dd' : activeTab === 'weekly' ? 'yyyy 第 WW 周' : 'yyyy-MM'"
              :value-format="activeTab === 'daily' ? 'yyyy-MM-dd' : activeTab === 'weekly' ? 'yyyy-MM-dd' : 'yyyy-MM'"
              :picker-options="pickerOptions"
              placeholder="选择历史报告"
              @change="loadHistoryReport"
              clearable
              size="small"
            >
            </el-date-picker>

            <el-button
              v-if="selectedHistoryDate"
              @click="clearHistorySelection"
              type="text"
              class="clear-selection-btn"
              size="small"
            >
              <i class="fa fa-times"></i> 清除
            </el-button>

            <div class="current-report-info" v-if="isViewingHistory">
              <i class="fa fa-history"></i>
              <span>历史报告</span>
            </div>
          </div>
        </div>

        <div class="header-info">
          <div class="date-info">
            <span>报告日期:</span>
            <span class="date-value">{{ currentDate }}</span>
          </div>
        </div>
      </div>

      <!-- 主要内容区域 -->
      <div class="main-content">
        <!-- 左侧：健康指标 -->
        <div class="health-indicators">
          <!-- 健康指标卡片 -->
          <div
            class="health-card"
            v-for="metric in healthMetricsList"
            :key="metric.key"
            @click="showChartModal(metric.key)"
          >
            <div class="card-header">
              <div class="card-title">
                <h3>{{ metric.title }}</h3>
                <p>{{ metric.subtitle }}</p>
              </div>
              <div class="card-icon" :class="metric.iconClass">
                <i :class="metric.icon"></i>
              </div>
            </div>

            <div class="card-body">
              <div class="metric-value">
                <span class="value">{{ formatValue(metric.data.average) }}</span>
                <span class="unit">{{ metric.unit }}</span>
              </div>
              <div class="metric-status" :class="metric.data.statusClass">
                <i :class="metric.data.statusIcon"></i>
                {{ metric.data.status }}
              </div>
            </div>

            <div class="chart-container">
              <div :ref="`${metric.key}ChartMini`" class="mini-chart"></div>
            </div>

            <!-- 卡片内健康建议 -->
            <div class="health-advice" :class="getAdviceClass(metric.data.statusClass)">
              <div class="advice-header">
                <i class="fa fa-lightbulb-o advice-icon"></i>
                <h4 class="advice-title">今日健康建议</h4>
              </div>
              <p class="advice-content">{{ metric.data.recommendations }}</p>
            </div>
          </div>
        </div>

        <!-- 右侧：健康分析与建议 -->
        <div class="health-analysis">
          <!-- 健康评分 -->
          <div class="analysis-card">
            <h3 class="analysis-title">健康评分</h3>

            <div class="score-container">
              <div class="chart-wrapper">
                <div ref="healthScoreChart" class="score-chart"></div>
                <div class="score-info">
                  <span class="score-value">{{ healthScore }}</span>
                  <span class="score-text">{{ healthScoreText }}</span>
                </div>
              </div>
            </div>

            <div class="score-description">
              <p>{{ healthScoreDescription }}</p>
            </div>
          </div>

          <!-- 健康隐患 -->
          <div class="analysis-card">
            <h3 class="analysis-title with-icon">
              <i class="fa fa-exclamation-triangle risk-icon"></i>健康隐患
            </h3>

            <div class="risks-container">
              <div v-for="risk in healthRisks" :key="risk.id" class="risk-item" :class="risk.bgClass">
                <div class="risk-icon-container" :class="risk.iconClass">
                  <i :class="risk.riskIcon"></i>
                </div>
                <div class="risk-content">
                  <h4 class="risk-title">{{ risk.riskTitle }}</h4>
                  <p class="risk-description">{{ risk.riskDescription }}</p>
                </div>
              </div>
            </div>
          </div>

          <!-- 健康建议 -->
          <div class="analysis-card">
            <h3 class="analysis-title with-icon">
              <i class="fa fa-lightbulb-o suggestion-icon"></i>健康建议
            </h3>

            <div class="suggestions-container">
              <div v-for="suggestion in healthSuggestions" :key="suggestion.id" class="suggestion-item">
                <div class="suggestion-icon-container" :class="suggestion.iconClass">
                  <i :class="suggestion.suggestionIcon"></i>
                </div>
                <div class="suggestion-content">
                  <h4 class="suggestion-title">{{ suggestion.suggestionTitle }}</h4>
                  <p class="suggestion-description">{{ suggestion.suggestionDescription }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表模态框 -->
    <el-dialog
      :visible.sync="modalVisible"
      :title="modalData.title"
      width="60%"
      :before-close="closeModal"
      class="chart-dialog"
      append-to-body
    >
      <div class="dialog-content">
        <div class="metric-info">
          <div class="metric-description">{{ modalData.info }}</div>
          <div class="normal-range">
            <span class="label">正常范围:</span>
            <span class="value">{{ modalData.normalRange }}{{ modalData.unit }}</span>
          </div>
        </div>
        <div class="chart-container-large">
          <div ref="modalChart" class="large-chart" style="width: 100%; height: 300px;"></div>
        </div>
      </div>

      <div class="health-advice-modal" :class="getAdviceClass(modalData.statusClass)">
        <div class="advice-header-modal">
          <i class="fa fa-lightbulb-o advice-icon-modal"></i>
          <h3 class="advice-title-modal">健康建议</h3>
        </div>
        <div class="advice-content-wrapper">
          <p class="advice-content-modal">{{ modalData.recommendations }}</p>
          <div class="advice-highlight" v-if="modalData.statusClass && modalData.statusClass.includes('warning')">
            <i class="fa fa-exclamation-circle"></i>
            <span>请特别关注此指标，及时采取措施</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import * as echarts from 'echarts'
import {getReportStatistics} from "@/api/health/healthReport";

import healthDataService from './js/HealthDataService.js'

export default {
  name: 'Report',
  data() {
    return {
      customerId: null,
      activeTab: 'daily',
      modalVisible: false,
      modalData: {},
      modalChartInstance: null,

      // 基本信息
      currentDate: '',
      avatarUrl: '',

      // 历史报告选择
      selectedHistoryDate: '',
      isViewingHistory: false,

      // 历史报告选择器选项
      pickerOptions: {
        disabledDate: null // 将在created钩子中初始化
      },

      // 健康评分
      healthScore: 0,
      healthScoreText: '',
      healthScoreDescription: '',

      // 健康风险
      healthRisks: [],

      // 健康建议
      healthSuggestions: [],

      // 健康指标配置
      healthMetricsConfig: {},

      // 月度特殊指标
      monthlyMetrics: {},


      // 健康指标数据
      healthMetrics: {},

      // 选项卡配置
      tabs: [
        {
          key: 'daily',
          label: '日',
          iconClass: 'fa fa-calendar-o'
        },
        {
          key: 'weekly',
          label: '周',
          iconClass: 'fa fa-calendar'
        },
        {
          key: 'monthly',
          label: '月',
          iconClass: 'fa fa-calendar-check-o'
        }
      ],

      // 图表引用
      miniCharts: {},
      healthScoreChartInstance: null
    }
  },
  computed: {
    healthMetricsList() {
      return Object.keys(this.healthMetrics).map(key => {
        return {
          key,
          ...this.healthMetricsConfig[key],
          data: this.healthMetrics[key]
        }
      })
    }
  },
  watch: {
    // 监听模态框可见性变化
    modalVisible(newVal) {
      if (newVal) {
        // 模态框打开后延迟初始化图表
        this.$nextTick(() => {
          if (this.modalData && this.modalData.title) {
            // 通过标题找到对应的类型
            const type = Object.keys(this.healthMetricsConfig).find(
              key => this.getMetricTitle(key) === this.modalData.title
            )
            if (type) {
              this.initModalChart(type)
            }
          }
        })
      } else {
        // 模态框关闭时销毁图表
        this.disposeModalChart()
      }
    }
  },
  async created() {
    this.customerId = this.$route.params && this.$route.params.customerId
    // 初始化日期选择器的禁用规则
    this.pickerOptions.disabledDate = this.getDisabledDateFunction();
    // 页面创建时加载数据
   // await this.loadHealthReportData()
  },
  mounted() {
    this.$nextTick(() => {
      // 使用更长的延迟确保DOM完全渲染
      // 设置默认选中的最新日期
      this.setDefaultLatestDate();
    })
  },
  beforeDestroy() {
    this.disposeAllCharts()
  },
  methods: {
    /**
     * 获取禁用日期函数
     */
    getDisabledDateFunction() {
      return (time) => {
        // 禁用未来日期
        if (time.getTime() > Date.now()) {
          return true;
        }

        // 禁用当天/当周/当月（根据当前activeTab）
        const today = new Date();
        today.setHours(0, 0, 0, 0);

        switch (this.activeTab) {
          case 'daily':
            // 禁用今天及未来日期（日报是第二天凌晨生成，所以今天还没有生成）
            return time.getTime() >= today.getTime();

          case 'weekly':
            // 禁用当前周及未来周（周报是下周一凌晨生成）
            const currentWeekStart = new Date(today);
            currentWeekStart.setDate(today.getDate() - today.getDay() + 1); // 本周一
            const selectedWeekStart = new Date(time);
            selectedWeekStart.setDate(time.getDate() - time.getDay() + 1); // 选中日期所在周的周一
            return selectedWeekStart.getTime() >= currentWeekStart.getTime();

          case 'monthly':
            // 禁用当前月及未来月（月报是下月1号凌晨生成）
            const currentMonth = new Date(today.getFullYear(), today.getMonth(), 1);
            const selectedMonth = new Date(time.getFullYear(), time.getMonth(), 1);
            return selectedMonth.getTime() >= currentMonth.getTime();

          default:
            return time.getTime() > Date.now();
        }
      };
    },

    /**
     * 加载健康报告数据
     */
    async loadHealthReportDataByMock() {
      try {
        const data = await healthDataService.getHealthReportData(this.activeTab)

        // 更新数据
        this.currentDate = data.basicInfo.currentDate
        this.avatarUrl = data.basicInfo.avatarUrl
        this.healthScore = data.healthScore.score
        this.healthScoreText = data.healthScore.text
        this.healthScoreDescription = data.healthScore.description
        this.healthRisks = data.healthRisks
        this.healthSuggestions = data.healthSuggestions
        this.healthMetricsConfig = data.healthMetricsConfig
        this.healthMetrics = data.healthMetrics
        this.tabs = data.tabs

        // 月度特殊指标
        this.monthlyMetrics = data.monthlyMetrics || {}
      } catch (error) {
        console.error('加载健康报告数据失败:', error)
        this.$message.error('数据加载失败')
      }
      this.$nextTick(() => {
        this.disposeAllCharts();
        this.initAllCharts();
      });
    },
    /**
     * 加载健康报告数据
     */
    async loadHealthReportData() {
     // await this.loadHealthReportDataByMock()
     // return
      try {

        getReportStatistics(this.customerId, this.activeTab, {
          reportPeriod: this.selectedHistoryDate ? this.formatReportPeriod(this.selectedHistoryDate) : null
        }).then(response => {
          if (response.code === 200 && response.data) {
            const data = response.data;

            // 更新数据
            this.currentDate = data.basicInfo ? data.basicInfo.currentDate : '';
            this.avatarUrl = data.basicInfo ? data.basicInfo.avatarUrl : '';
            this.healthScore = data.healthScore ? data.healthScore.score : 0;
            this.healthScoreText = data.healthScore ? data.healthScore.text : '';
            this.healthScoreDescription = data.healthScore ? data.healthScore.description : '';

            // 如果后端返回了完整的数据结构，则使用后端数据
            // 否则保留原有的mock数据结构
            if (data.healthRisks) this.healthRisks = data.healthRisks;
            if (data.healthSuggestions) this.healthSuggestions = data.healthSuggestions;
            if (data.healthMetricsConfig) this.healthMetricsConfig = data.healthMetricsConfig;
            if (data.healthMetrics) this.healthMetrics = data.healthMetrics;
            if (data.monthlyMetrics) this.monthlyMetrics = data.monthlyMetrics;

            // 初始化图表
            this.$nextTick(() => {
              this.disposeAllCharts();
              this.initAllCharts();
            });
          } else {
            console.error('加载健康报告数据失败:', response.msg)
            this.$message.error('数据加载失败: ' + response.msg)
          }
        })
      } catch (error) {
        console.error('加载健康报告数据失败:', error)
        this.$message.error('数据加载失败')
      }
    },

    /**
     * 格式化报告周期
     */
    formatReportPeriod(date) {
      if (!date) return null

      const d = new Date(date)
      switch (this.activeTab) {
        case 'daily':
          // 返回格式: 2023-10-25
          return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
        case 'weekly':
          // 返回格式: 2023-W43 (需要计算周数)
          const weekNumber = this.getWeekNumber(d)
          return `${d.getFullYear()}-W${String(weekNumber).padStart(2, '0')}`
        case 'monthly':
          // 返回格式: 2023-10
          return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`
        default:
          return null
      }
    },

    /**
     * 计算周数
     */
    getWeekNumber(d) {
      // 复制日期对象避免修改原对象
      const date = new Date(d.getTime())
      date.setHours(0, 0, 0, 0)
      // 设置为周四，确保在同一周内
      date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7)
      // 1月4日总是在第一周
      const week1 = new Date(date.getFullYear(), 0, 4)
      // 调整为周一
      week1.setDate(week1.getDate() - (week1.getDay() + 6) % 7)
      // 计算周数
      const weekNumber = 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7)
      return weekNumber
    },

    /**
     * 切换时间选项卡
     */
    async switchTab(tabKey) {
      this.activeTab = tabKey
      // 清除历史选择
      this.selectedHistoryDate = ''
      this.isViewingHistory = false
      // 更新日期选择器的禁用规则
      this.$set(this.pickerOptions, 'disabledDate', this.getDisabledDateFunction())

      // 设置默认选中最新的可选时间
      this.$nextTick(() => {
        this.setDefaultLatestDate();
      });
    },
    /**
     * 设置默认选中最新的可选时间
     */
    setDefaultLatestDate() {
      // 创建一个新的日期对象，表示昨天、上周或上个月
      const now = new Date();

      switch (this.activeTab) {
        case 'daily':
          // 日报默认选中昨天
          const yesterday = new Date(now);
          yesterday.setDate(now.getDate() - 1);
          this.selectedHistoryDate = this.formatDate(yesterday, 'yyyy-MM-dd');
          break;

        case 'weekly':
          // 周报默认选中上周
          const lastWeek = new Date(now);
          lastWeek.setDate(now.getDate() - 7);
          // 获取上周一的日期
          const lastMonday = new Date(lastWeek);
          lastMonday.setDate(lastWeek.getDate() - lastWeek.getDay() + 1);
          this.selectedHistoryDate = this.formatDate(lastMonday, 'yyyy-MM-dd');
          break;

        case 'monthly':
          // 月报默认选中上个月
          const lastMonth = new Date(now);
          lastMonth.setMonth(now.getMonth() - 1);
          // 设置为上个月的第一天
          lastMonth.setDate(1);
          this.selectedHistoryDate = this.formatDate(lastMonth, 'yyyy-MM');
          break;

        default:
          break;
      }

      // 触发历史报告加载
      if (this.selectedHistoryDate) {
        this.loadHistoryReport(this.selectedHistoryDate);
      }

      // 强制更新时间选择器组件
      this.$nextTick(() => {
        if (this.$refs.historyDatePicker) {
          // 重置时间选择器的状态
          this.$refs.historyDatePicker.blur();
        }
      });
    },
    /**
     * 格式化日期
     */
    formatDate(date, format) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');

      if (format === 'yyyy-MM-dd') {
        return `${year}-${month}-${day}`;
      } else if (format === 'yyyy-MM') {
        return `${year}-${month}`;
      }
      return date.toISOString();
    },
    /**
     * 加载历史报告
     */
    async loadHistoryReport(date) {

      if (!date) {
        // 如果没有选择日期，回到最新报告
        this.isViewingHistory = false
        await this.loadHealthReportData()
        this.$nextTick(() => {
          this.disposeAllCharts()
          this.initAllCharts()
        })
        return
      }

      try {
        this.isViewingHistory = true
        // 调用获取历史报告的API
        this.loadHealthReportData()


      } catch (error) {
        console.error('加载历史报告数据失败:', error)
        this.$message.error('历史报告数据加载失败')
      }
    },

    /**
     * 清除历史选择
     */
    clearHistorySelection() {
      this.selectedHistoryDate = ''
      this.isViewingHistory = false
      this.loadHealthReportData()
      this.setDefaultLatestDate()
    },

    // 获取建议框的样式类
    getAdviceClass(statusClass) {
      if (statusClass && statusClass.includes('warning')) {
        return 'health-advice-warning'
      }
      return ''
    },

    // 初始化所有图表
    initAllCharts() {
      this.initMiniCharts()
      this.initHealthScoreChart()
    },

    // 销毁所有图表
    disposeAllCharts() {
      // 销毁小图表
      Object.keys(this.miniCharts).forEach(key => {
        if (this.miniCharts[key]) {
          try {
            // 移除resize事件监听器
            if (this.miniCharts[key]._handleResize) {
              window.removeEventListener('resize', this.miniCharts[key]._handleResize)
            }
            this.miniCharts[key].dispose()
          } catch (e) {
            console.error('销毁图表失败:', key, e)
          }
        }
      })
      this.miniCharts = {}

      // 销毁健康评分图表
      if (this.healthScoreChartInstance) {
        try {
          // 移除resize事件监听器
          if (this.healthScoreChartInstance._handleResize) {
            window.removeEventListener('resize', this.healthScoreChartInstance._handleResize)
          }
          this.healthScoreChartInstance.dispose()
        } catch (e) {
          console.error('销毁健康评分图表失败:', e)
        }
        this.healthScoreChartInstance = null
      }

      // 销毁模态框图表
      this.disposeModalChart()
    },

    // 初始化小型图表
    initMiniCharts() {
      this.healthMetricsList.forEach((metric) => {
        try {
          // 确保DOM元素存在
          this.$nextTick(() => {
            const chartRef = this.$refs[`${metric.key}ChartMini`]
            if (chartRef && chartRef.length > 0 && chartRef[0]) {
              const chartDom = chartRef[0]
              // 检查元素是否有尺寸
              if (chartDom.offsetWidth > 0 && chartDom.offsetHeight > 0) {
                // 销毁已存在的图表
                if (this.miniCharts[metric.key]) {
                  try {
                    this.miniCharts[metric.key].dispose()
                  } catch (e) {
                    console.error(`销毁已存在的图表失败 ${metric.key}:`, e)
                  }
                }

                // 初始化新图表
                const chart = echarts.init(chartDom)

                let option
                switch (metric.key) {
                  case 'bloodPressure':
                    option = {
                      grid: {
                        left: '10',
                        right: '10',
                        top: '20',
                        bottom: '30'
                      },
                      xAxis: {
                        type: 'category',
                        show: true,
                        axisLine: {show: true},
                        axisTick: {show: true},
                        axisLabel: {
                          show: true,
                          fontSize: 8,
                          color: '#999',
                          rotate: 45
                        },
                        boundaryGap: false,
                        data: metric.data.data.labels
                      },
                      yAxis: {
                        show: false,
                        type: 'value'
                      },
                      series: [
                        {
                          name: '收缩压',
                          type: 'line',
                          showSymbol: true,
                          symbolSize: 6,
                          smooth: true,
                          lineStyle: {
                            width: 2,
                            color: metric.color[0]
                          },
                          data: metric.data.data.systolic || [],
                          areaStyle: null,
                          label: {
                            show: true,
                            position: 'top',
                            fontSize: 10,
                            color: metric.color[0],
                            formatter: '{c}',
                            distance: 5
                          }
                        },
                        {
                          name: '舒张压',
                          type: 'line',
                          showSymbol: true,
                          symbolSize: 6,
                          smooth: true,
                          lineStyle: {
                            width: 2,
                            color: metric.color[1]
                          },
                          data: metric.data.data.diastolic || [],
                          areaStyle: null,
                          label: {
                            show: true,
                            position: 'bottom',
                            fontSize: 10,
                            color: metric.color[1],
                            formatter: '{c}',
                            distance: 5
                          }
                        }
                      ],
                      tooltip: {
                        show: true,
                        trigger: 'axis'
                      },
                      legend: {
                        show: false
                      }
                    }
                    break

                  case 'sleep':
                    // 判断是日报还是周报/月报数据结构
                    if (metric.data.data.deep) {
                      // 日报数据结构 - 显示深度睡眠
                      option = {
                        grid: {
                          left: '10',
                          right: '10',
                          top: '20',
                          bottom: '30'
                        },
                        xAxis: {
                          type: 'category',
                          show: true,
                          axisLine: {show: true},
                          axisTick: {show: true},
                          axisLabel: {
                            show: true,
                            fontSize: 8,
                            color: '#999',
                            rotate: 45
                          },
                          data: metric.data.data.labels
                        },
                        yAxis: {
                          show: false,
                          type: 'value'
                        },
                        series: [{
                          name: '深度睡眠',
                          type: 'bar',
                          barWidth: '60%',
                          data: metric.data.data.deep || [],
                          itemStyle: {
                            borderRadius: [4, 4, 0, 0],
                            color: metric.color
                          },
                          label: {
                            show: true,
                            position: 'top',
                            fontSize: 10,
                            color: metric.color,
                            formatter: '{c}',
                            distance: 2
                          }
                        }],
                        tooltip: {
                          show: true,
                          trigger: 'axis'
                        },
                        legend: {
                          show: false
                        }
                      }
                    } else {
                      // 周报/月报数据结构 - 显示睡眠时长
                      option = {
                        grid: {
                          left: '10',
                          right: '10',
                          top: '20',
                          bottom: '30'
                        },
                        xAxis: {
                          type: 'category',
                          show: true,
                          axisLine: {show: true},
                          axisTick: {show: true},
                          axisLabel: {
                            show: true,
                            fontSize: 8,
                            color: '#999',
                            rotate: 45
                          },
                          data: metric.data.data.labels
                        },
                        yAxis: {
                          show: false,
                          type: 'value'
                        },
                        series: [{
                          name: '睡眠时长',
                          type: 'bar',
                          barWidth: '60%',
                          data: metric.data.data.values || [],
                          itemStyle: {
                            borderRadius: [4, 4, 0, 0],
                            color: metric.color
                          },
                          label: {
                            show: true,
                            position: 'top',
                            fontSize: 10,
                            color: metric.color,
                            formatter: '{c}',
                            distance: 2
                          }
                        }],
                        tooltip: {
                          show: true,
                          trigger: 'axis'
                        },
                        legend: {
                          show: false
                        }
                      }
                    }
                    break

                  case 'steps':
                    option = {
                      grid: {
                        left: '10',
                        right: '10',
                        top: '20',
                        bottom: '30'
                      },
                      xAxis: {
                        type: 'category',
                        show: true,
                        axisLine: {show: true},
                        axisTick: {show: true},
                        axisLabel: {
                          show: true,
                          fontSize: 8,
                          color: '#999',
                          rotate: 45
                        },
                        data: metric.data.data.labels
                      },
                      yAxis: {
                        show: false,
                        type: 'value'
                      },
                      series: [{
                        name: '步数',
                        type: 'bar',
                        barWidth: '60%',
                        data: metric.data.data.values || [],
                        itemStyle: {
                          borderRadius: [4, 4, 0, 0],
                          color: metric.color
                        },
                        label: {
                          show: true,
                          position: 'top',
                          fontSize: 10,
                          color: metric.color,
                          formatter: '{c}',
                          distance: 2
                        }
                      }],
                      tooltip: {
                        show: true,
                        trigger: 'axis'
                      },
                      legend: {
                        show: false
                      }
                    }
                    break

                  default:
                    option = {
                      grid: {
                        left: '10',
                        right: '10',
                        top: '20',
                        bottom: '30'
                      },
                      xAxis: {
                        type: 'category',
                        show: true,
                        axisLine: {show: true},
                        axisTick: {show: true},
                        axisLabel: {
                          show: true,
                          fontSize: 8,
                          color: '#999',
                          rotate: 45
                        },
                        boundaryGap: false,
                        data: metric.data.data.labels
                      },
                      yAxis: {
                        show: false,
                        type: 'value'
                      },
                      series: [{
                        name: metric.title,
                        type: 'line',
                        showSymbol: true,
                        symbolSize: 6,
                        smooth: true,
                        lineStyle: {
                          width: 2,
                          color: Array.isArray(metric.color) ? metric.color[0] : metric.color
                        },
                        data: metric.data.data.values || [],
                        areaStyle: {
                          color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                              offset: 0,
                              color: Array.isArray(metric.color) ? metric.color[0] + '4D' : metric.color + '4D'
                            }, {
                              offset: 1,
                              color: Array.isArray(metric.color) ? metric.color[0] + '0D' : metric.color + '0D'
                            }]
                          }
                        },
                        label: {
                          show: true,
                          position: 'top',
                          fontSize: 10,
                          color: Array.isArray(metric.color) ? metric.color[0] : metric.color,
                          formatter: '{c}',
                          distance: 5
                        }
                      }],
                      tooltip: {
                        show: true,
                        trigger: 'axis'
                      },
                      legend: {
                        show: false
                      }
                    }
                }

                chart.setOption(option, true)
                this.miniCharts[metric.key] = chart

                // 添加窗口大小调整监听
                const handleResize = () => {
                  if (chart && !chart.isDisposed()) {
                    chart.resize()
                  }
                }
                window.addEventListener('resize', handleResize)
                chart._handleResize = handleResize
              }
            }
          })
        } catch (error) {
          console.error(`初始化图表失败 ${metric.key}:`, error)
        }
      })
    },

    // 初始化健康评分图表
    initHealthScoreChart() {
      try {
        this.$nextTick(() => {
          const chartRef = this.$refs.healthScoreChart
          if (chartRef) {
            const chartDom = chartRef
            if (chartDom.offsetWidth > 0 && chartDom.offsetHeight > 0) {
              // 销毁已存在的图表
              if (this.healthScoreChartInstance) {
                try {
                  this.healthScoreChartInstance.dispose()
                } catch (e) {
                  console.error('销毁已存在的健康评分图表失败:', e)
                }
              }

              // 初始化新图表
              const chart = echarts.init(chartDom)
              const option = {
                series: [{
                  type: 'pie',
                  radius: ['70%', '90%'],
                  avoidLabelOverlap: false,
                  label: {
                    show: false
                  },
                  emphasis: {
                    label: {
                      show: false
                    }
                  },
                  labelLine: {
                    show: false
                  },
                  data: [
                    {
                      value: this.healthScore,
                      itemStyle: {color: '#165DFF'},
                      name: '得分'
                    },
                    {
                      value: 100 - this.healthScore,
                      itemStyle: {color: '#E2E8F0'},
                      name: '剩余'
                    }
                  ]
                }]
              }

              chart.setOption(option, true)
              this.healthScoreChartInstance = chart

              // 添加窗口大小调整监听
              const handleResize = () => {
                if (chart && !chart.isDisposed()) {
                  chart.resize()
                }
              }
              window.addEventListener('resize', handleResize)
              chart._handleResize = handleResize
            }
          }
        })
      } catch (error) {
        console.error('初始化健康评分图表失败:', error)
      }
    },

    // 显示图表模态框
    async showChartModal(type) {
      try {
        // 这里应该调用后端API获取特定指标的详细数据
        // 暂时使用模拟数据
        const metricData = this.getMockMetricData(type);
        console.log('metricData:', metricData)
        this.modalData = {
          ...metricData.data,
          title: this.getMetricTitle(type),
          unit: metricData.config.unit,
          normalRange: metricData.config.normalRange
        }
        this.modalVisible = true
      } catch (error) {
        console.error('获取指标数据失败:', error)
        this.$message.error('数据获取失败')
      }
    },

    // 获取模拟指标数据（临时使用，应该从后端获取）
    getMockMetricData(type) {
      // 这里应该从后端获取真实数据
      // 为了保持页面功能，暂时返回模拟数据
      return {
        config: this.healthMetricsConfig[type],
        data:this.healthMetrics[type]
      }

    },

    // 获取指标标题
    getMetricTitle(type) {
      const titles = {
        heartRate: '心率详情',
        ecg: '心电详情',
        bloodPressure: '血压详情',
        bloodSugar: '血糖详情',
        oxygenLevel: '血氧详情',
        sleep: '睡眠详情',
        steps: '步数详情'
      }
      return titles[type] || ''
    },

    // 初始化模态框图表
    initModalChart(type) {
      try {
        const chartRef = this.$refs.modalChart
        if (chartRef && this.modalVisible) {
          // 销毁已存在的图表
          this.disposeModalChart()

          // 确保元素可见且有尺寸
          // 初始化新图表
          const chart = echarts.init(chartRef)
          const option = this.getChartConfig(type)
          chart.setOption(option, true)
          this.modalChartInstance = chart

          // 添加窗口大小调整监听
          const handleResize = () => {
            if (chart && !chart.isDisposed()) {
              chart.resize()
            }
          }
          window.addEventListener('resize', handleResize)
          chart._handleResize = handleResize


        }
      } catch (error) {
        console.error('初始化模态框图表失败:', error)
      }
    },

    // 销毁模态框图表
    disposeModalChart() {
      if (this.modalChartInstance) {
        try {
          // 移除事件监听器
          if (this.modalChartInstance._handleResize) {
            window.removeEventListener('resize', this.modalChartInstance._handleResize)
          }
          // 销毁图表
          this.modalChartInstance.dispose()
        } catch (e) {
          console.error('销毁模态框图表失败:', e)
        }
        this.modalChartInstance = null
      }
    },

    // 获取图表配置
    getChartConfig(type) {
      const data = this.healthMetrics[type]
      const config = this.healthMetricsConfig[type]

      const baseOptions = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          show: (type === 'bloodPressure' || type === 'sleep'),
          top: 'top'
        },
        xAxis: {
          type: 'category',
          data: (data.data && data.data.labels) || [],
          name: '时间',
          boundaryGap: false,
        },
        yAxis: {
          type: 'value',
          name: `数值 (${config.unit})`
        }
      }

      switch (type) {
        case 'bloodPressure':
          console.log('config:', config)
          return {
            ...baseOptions,
            series: [
              {
                name: '收缩压',
                type: 'line',
                data: (data.data && data.data.systolic) || [],
                itemStyle: {color: config.color[0]},
                showSymbol: true,
                symbolSize: 8,
                label: {
                  show: true,
                  position: 'top',
                  fontSize: 12,
                  color: config.color[0],
                  formatter: '{c}',
                  distance: 5
                }
              },
              {
                name: '舒张压',
                type: 'line',
                data: (data.data && data.data.diastolic) || [],
                itemStyle: {color: config.color[1]},
                showSymbol: true,
                symbolSize: 8,
                label: {
                  show: true,
                  position: 'bottom',
                  fontSize: 12,
                  color: config.color[1],
                  formatter: '{c}',
                  distance: 5
                }
              }
            ]
          }

        case 'sleep':
          // 判断是日报还是周报/月报数据结构
          if (data.data && data.data.deep) {
            // 日报数据结构 - 显示详细睡眠阶段
            return {
              ...baseOptions,
              series: [
                {
                  name: '深度睡眠',
                  type: 'line',
                  data: (data.data && data.data.deep) || [],
                  itemStyle: {color: '#165DFF'},
                  areaStyle: {
                    color: 'rgba(22, 93, 255, 0.1)'
                  },
                  showSymbol: true,
                  symbolSize: 8,
                  label: {
                    show: true,
                    position: 'top',
                    fontSize: 12,
                    color: '#165DFF',
                    formatter: '{c}',
                    distance: 5
                  }
                },
                {
                  name: '浅度睡眠',
                  type: 'line',
                  data: (data.data && data.data.light) || [],
                  itemStyle: {color: '#36D399'},
                  showSymbol: true,
                  symbolSize: 8,
                  label: {
                    show: true,
                    position: 'top',
                    fontSize: 12,
                    color: '#36D399',
                    formatter: '{c}',
                    distance: 5
                  }
                },
                {
                  name: '清醒',
                  type: 'line',
                  data: (data.data && data.data.awake) || [],
                  itemStyle: {color: '#FB923C'},
                  showSymbol: true,
                  symbolSize: 8,
                  label: {
                    show: true,
                    position: 'top',
                    fontSize: 12,
                    color: '#FB923C',
                    formatter: '{c}',
                    distance: 5
                  }
                }
              ]
            }
          } else {
            // 周报/月报数据结构 - 显示睡眠时长
            return {
              ...baseOptions,
              series: [
                {
                  name: '睡眠时长',
                  type: 'line',
                  data: (data.data && data.data.values) || [],
                  itemStyle: {color: '#FB923C'},
                  areaStyle: {
                    color: 'rgba(251, 146, 60, 0.1)'
                  },
                  showSymbol: true,
                  symbolSize: 8,
                  label: {
                    show: true,
                    position: 'top',
                    fontSize: 12,
                    color: '#FB923C',
                    formatter: '{c}',
                    distance: 5
                  }
                }
              ]
            }
          }

        case 'steps':
          return {
            ...baseOptions,
            series: [{
              name: '步数',
              type: 'bar',
              data: (data.data && data.data.values) || [],
              itemStyle: {
                borderRadius: [4, 4, 0, 0],
                color: config.color
              },
              label: {
                show: true,
                position: 'top',
                fontSize: 12,
                color: config.color,
                formatter: '{c}',
                distance: 5
              }
            }]
          }

        default:
          return {
            ...baseOptions,
            series: [{
              name: `${this.getMetricTitle(type).split('详情')[0]} (${config.unit})`,
              type: 'line',
              data: (data.data && data.data.values) || [],
              itemStyle: {color: Array.isArray(config.color) ? config.color[0] : config.color},
              areaStyle: {
                color: `${Array.isArray(config.color) ? config.color[0] : config.color}33`
              },
              showSymbol: true,
              symbolSize: 8,
              label: {
                show: true,
                position: 'top',
                fontSize: 12,
                color: Array.isArray(config.color) ? config.color[0] : config.color,
                formatter: '{c}',
                distance: 5
              }
            }]
          }
      }
    },

    // 关闭模态框
    closeModal() {
      this.modalVisible = false
    },

    // 格式化数字显示（添加千位分隔符）
    formatNumber(num) {
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    },

    // 格式化值显示
    formatValue(value) {
      if (typeof value === 'number') {
        return this.formatNumber(value)
      }
      return value
    }
  }
}
</script>


<style scoped src="@/views/customer/health/scss/report.css"></style>
